from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required, user_passes_test
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse

from .forms import UserCreateForm, UserUpdateForm


# 个人设置页面视图
@login_required
def profile_view(request):
    """用户个人设置页面"""
    user = request.user
    
    if request.method == "POST":
        form = UserUpdateForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            messages.success(request, "个人设置已更新")
            return redirect(reverse("accounts:profile"))
    else:
        form = UserUpdateForm(instance=user)
    
    return render(request, "accounts/profile.html", {
        "form": form,
        "user": user,
        "title": "个人设置"
    })


def _is_staff_user(user) -> bool:
    return bool(user and user.is_authenticated and user.is_staff)


@login_required
@user_passes_test(_is_staff_user)
def user_list(request):
    """用户列表（仅管理员可见）"""
    User = get_user_model()
    users = User.objects.all().order_by("id")
    return render(request, "accounts/user_list.html", {"users": users})


@login_required
@user_passes_test(_is_staff_user)
def user_create(request):
    """创建用户（仅管理员）"""
    if request.method == "POST":
        form = UserCreateForm(request.POST)
        if form.is_valid():
            user = form.save()
            messages.success(request, f"已创建用户：{user.username}")
            return redirect(reverse("accounts:user_list"))
    else:
        form = UserCreateForm()
    return render(request, "accounts/user_form.html", {"form": form, "title": "创建用户"})


@login_required
@user_passes_test(_is_staff_user)
def user_update(request, user_id: int):
    """编辑用户（仅管理员）"""
    User = get_user_model()
    user = get_object_or_404(User, id=user_id)
    if request.method == "POST":
        form = UserUpdateForm(request.POST, instance=user)
        if form.is_valid():
            form.save()
            messages.success(request, f"已更新用户：{user.username}")
            return redirect(reverse("accounts:user_list"))
    else:
        form = UserUpdateForm(instance=user)
    return render(request, "accounts/user_form.html", {"form": form, "title": "编辑用户"})


@login_required
@user_passes_test(_is_staff_user)
def user_delete(request, user_id: int):
    """删除用户（仅管理员）"""
    User = get_user_model()
    user = get_object_or_404(User, id=user_id)
    if request.method == "POST":
        username = user.username
        user.delete()
        messages.success(request, f"已删除用户：{username}")
        return redirect(reverse("accounts:user_list"))
    return render(request, "accounts/user_confirm_delete.html", {"user": user})

# Create your views here.
